<template>
  <div class="app-container">
    
<br>
<br>
    <el-button type="primary" @click="add">添加临时部门</el-button>
    <br>
    <br>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    > 
      <el-table-column align="center" label="序号" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="临时部门名称" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.deptName }}
        </template>
      </el-table-column>
      <el-table-column label="临时工作地点" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.workAddressName }}
        </template>
      </el-table-column>
      <el-table-column label="有效期" width="250" align="center">
        <template slot-scope="scope">
          {{ scope.row.expiration.substring(0, 10) + ' ' + scope.row.expiration.substring(11, 19) }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" align="center" width="300" >
        <template slot-scope="scope">
          <el-button type="primary"  @click="getInfo(scope.row)" size="small">详情</el-button>
          <el-button type="warning" :loading="toUpdateBtnLoading" v-if="scope.row.canAudit" @click="approve(scope.row, true)" size="small">审批</el-button>
          <el-button type="danger" :loading="toUpdateBtnLoading" v-if="scope.row.canAudit" @click="approve(scope.row, false)" size="small">拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="->, total, prev, pager, next"
      :total="this.total"
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="clickCurPage"
      >
    </el-pagination>
  <el-dialog title="临时部门详情" :visible.sync="infoVisible">
      <h2>临时部门信息</h2>
      <el-form ref="info" :model="info" label-width="120px">
        <el-row :gutter=10>
          <el-col :span=8 >
            <el-form-item :label="(index+1)+'级审批'" v-for="(jobDuty, index) in this.auditPreset" :key="jobDuty.id" prop="auditPreset">
              <span>{{ jobDuty.name }}</span>
              <el-select v-model="jobDuty.auditUser" placeholder="请选择" style="width: 250px" :disabled="true">
                <el-option
                  v-for="item in jobDuty.auditAvailableUserList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span=8>
            <el-form-item label="临时工作部门" prop="deptId" >
              <el-select style="width:300px" v-model="info.deptId" placeholder="请选择" :disabled="true">
                <el-option
                  v-for="item in depts"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  @click.native="selectDept(item.id)"
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span=8 >
            <el-form-item label="临时工作地点" prop="workAddressId" >
              <el-select style="width:300px" v-model="info.workAddressId" placeholder="请选择" :disabled="true">
                <el-option
                  v-for="item in workAddresses"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span=8>
            <el-form-item label="到期时间" prop="expiration">
              <el-date-picker style="width:300px" :disabled="true"
                v-model="info.expiration"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
  </el-dialog>
  <el-dialog :title="dialogTitle" :visible.sync="formVisible" :closeOnClickModal="false">
      <h2>临时部门信息</h2>
      <el-form ref="form" :model="form" label-width="120px" :rules="formRules">
        <el-row :gutter=10>
          <el-col :span=8 >
            <el-form-item :label="(index+1)+'级审批'" v-for="(jobDuty, index) in this.auditPreset" :key="jobDuty.id" prop="auditPreset">
              <span>{{ jobDuty.name }}</span>
              <el-select v-model="jobDuty.auditUser" placeholder="请选择" style="width: 250px">
                <el-option
                  v-for="item in jobDuty.auditAvailableUserList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span=8>
            <el-form-item label="临时工作部门" prop="deptId" >
              <el-select style="width:300px" v-model="form.deptId" placeholder="请选择" >
                <el-option
                  v-for="item in depts"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  @click.native="selectDept(item.id)"
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span=8 >
            <el-form-item label="临时工作地点" prop="workAddressId" >
              <el-select style="width:300px" v-model="form.workAddressId" placeholder="请选择" :disabled="workAddressIsDisabled">
                <el-option
                  v-for="item in workAddresses"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span=8>
            <el-form-item label="到期时间" prop="expiration">
              <el-date-picker style="width:300px"
                v-model="form.expiration"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirm">确 定</el-button>
          <div style="width:200px;display: inline-block;"> </div>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
  </el-dialog>
  </div>
</template>

<script>

import { getTempListForAll, getList as deptList } from '@/api/dept'
import { getListByDeptId as getWorkAddressListByDeptId, getList as getWorkAddressList } from '@/api/workAddress'
import { audit, getList as getAuditList, getInfo as getAuditInfo } from '@/api/auditFlow'

export default {
  filters: {

  },
  data() {
    const validateDept = (rule, value, callback) => {
      if (!this.form.deptId) callback(new Error('请选择工作部门')) 
      else callback()
    }
    const validateWorkAddress = (rule, value, callback) => {
      if (!this.form.workAddressId) callback(new Error('请选择工作地点')) 
      else callback()
    }
    const validateExpiration = (rule, value, callback) => {
      if (!this.form.expiration) callback(new Error('请选择到期时间')) 
      else callback()
    }
    const validateAuditPreset = (rule, value, callback) => {
      for (let index = 0; index < this.auditPreset.length; index++) {
        if(!this.auditPreset[index].auditUser) callback(new Error('请选择审批人'))
      }
      callback()
    }
    
    return {
      list: null,
      listLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      info: {},
      form: {},
      dialogTitle: '添加临时部门',
      depts:[],
      formRules: {
        deptId: [{ required: true, trigger: 'blur', validator: validateDept }],
        workAddressId: [{ required: true, trigger: 'blur', validator: validateWorkAddress }],
        expiration: [{ required: true, trigger: 'blur', validator: validateExpiration }],
        auditPreset: [{ required: true, trigger: 'blur', validator: validateAuditPreset }],
      },
      workAddresses: [],
      workAddressIsDisabled: true,
      auditPreset: [],
      toUpdateBtnLoading: false,
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getTempListForAll({currentPage: this.currentPage, pageSize: this.pageSize}).then(res=>{
        console.log(res)
        this.list = res.data.records
        this.total = res.data.length
        this.listLoading = false
      }).catch(err=>{
        console.log("err")
        console.log(err)
        this.listLoading = false
      })
      deptList({currentPage: 1, pageSize: 100}).then(deptRes=>{
        this.depts = deptRes.data
      })
      getAuditInfo({businessCode: 'apply_tmp_dept'}).then(res=> {
        this.auditPreset = res.data
      })
      getWorkAddressList().then(workAddressRes=> {
        this.workAddresses = workAddressRes.data
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    getInfo(row) {
      this.info = row
      this.auditPreset = this.info.auditFlowDetail.jobDutyList
      this.infoVisible = true
    },
    update(row) {
      this.reset()
      this.dialogTitle = '修改临时部门'
      this.form = JSON.parse(JSON.stringify(row))
      this.auditPreset = this.form.auditFlowDetail.jobDutyList
      this.formVisible = true
    },
    deleteInfo(scope) {
      console.log(scope.row)
      this.$confirm('确定删除该临时部门?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(scope.row.id).then(res=>{
          this.list.splice(scope.$index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(err=>{
          console.log(err)
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    add(row) {
      this.reset()
      this.dialogTitle = '添加临时部门'
      this.formVisible = true
    },
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.auditUserIds = this.auditPreset.map(jobDutyVo => Number(jobDutyVo.auditUser))
          if(this.form.id) {  // update
            console.log(this.form)
            edit(this.form).then(res=>{
              console.log(res)
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.formVisible = false
              this.listLoading = false
              this.$tab.refreshPage({path: '/dept/tmpDeptList', name: "TmpDeptList"});
            }).catch(err=>{
              console.log(err)
            })
          } else { // add
            console.log(this.form)
            addTempDept(this.form).then(res=>{
              this.formVisible = false
              this.listLoading = false
              this.$tab.refreshPage({path: '/dept/tmpDeptList', name: "TmpDeptList"});
            }).catch(err=>{
              console.log(err)
            })
          }
        }
      })
    },
    cancel() {
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    selectDept(deptId) {
      this.workAddressIsDisabled = true
      this.jobDutyIsDisabled = true
      this.$set(this.form, 'workAddressId', undefined)
      getWorkAddressListByDeptId({'deptId' : deptId}).then(workAddressRes=> {
        console.log('workAddresses: ', workAddressRes.data)
        this.workAddresses = workAddressRes.data
        this.workAddressIsDisabled = false
      })
    },
    approve(row, pass) {
      console.log(row)
      this.toUpdateBtnLoading = true
      audit({flowNo: row.code, pass: pass}).then(auditRes=> {
        console.log("auditRes", auditRes)
        this.toUpdateBtnLoading = false
        this.fetchData()
      })
    },
  }
}
</script>
